package com.ocr;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import net.daum.adam.publisher.AdView;

import com.ocr.*;
import com.adapter.HistoryAdapter;
import com.dao.HistoryDAO;
import com.entity.HistoryItem;
import com.entity.Language;
import com.entity.LanguageContext;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdRequest;
import com.jabistudio.androidjhlabs.filter.ContrastFilter;
import com.jabistudio.androidjhlabs.filter.DoGFilter;
import com.jabistudio.androidjhlabs.filter.ReduceNoiseFilter;
import com.jabistudio.androidjhlabs.filter.util.AndroidUtils;
import com.util.OCRCostant;
import com.util.ProcessImgUtil;

import android.media.ExifInterface;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TableLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	// private Button btnShowHistory;
	private Button btnSelectAlbum;
	private Button btnSelectCamera;
	private ProgressDialog progressDialog;
	public static Boolean loaded = false;
	public static HistoryDAO HISTORY_DAO;
	private ImageView imgMenu;
	public static Uri imgUri;
	private ImageView imgBanner;
	private LinearLayout layoutAdmod;
	private com.google.android.gms.ads.AdView adView;
	private static final String AD_UNIT_ID = "a152dff86771917";
	public static int OCR_MODE = 1;// 1 mormal, 2 quickly, 3 accurate
	// do sang cua hình để xem co xu ly anh k
	public static int IMG_BRIGHTNESS_NUM;
	/*
	 * tessdata
	 */
	public static final String DATA_PATH = Environment
			.getExternalStorageDirectory().toString() + "/OCR/";

	public void copyAssetToStoreage(String lang) {
		if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata"))
				.exists()) {
			try {

				AssetManager assetManager = getAssets();
				InputStream in = assetManager.open("tessdata/" + lang
						+ ".traineddata");
				OutputStream out = new FileOutputStream(DATA_PATH + "tessdata/"
						+ lang + ".traineddata");
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();

			} catch (IOException e) {
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*
		 * copy tessdata to storeage
		 */
		String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };

		for (String path : paths) {
			File dir = new File(path);
			if (!dir.exists()) {
				if (!dir.mkdirs()) {
					Log.d("----copyed", "");
					return;
				} else {

				}
			}

		}

		copyAssetToStoreage(OCRCostant.ENG);
		// copyAssetToStoreage(OCRCostant.JAPANESE);
		copyAssetToStoreage(OCRCostant.VIE);
		copyAssetToStoreage(OCRCostant.VIE_ARIAL);
		copyAssetToStoreage(OCRCostant.VIE_COURIER_NEW);
		copyAssetToStoreage(OCRCostant.VIE_SOUTHERN);
		copyAssetToStoreage(OCRCostant.VIE_TAHOMA);
		//copyAssetToStoreage(OCRCostant.VIE_TIME_NEW_ROMAN);
		copyAssetToStoreage(OCRCostant.VIE_VERDANA);
		copyAssetToStoreage(OCRCostant.VIE_VNBOOKANTIQUA_TCVN3);
		/*
		 * 
		 * 
		 */
		setContentView(R.layout.activity_main);
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getResources().getString(
				R.string.message_please_wait));
		progressDialog.setTitle("");
		progressDialog.setIndeterminate(true);

		HISTORY_DAO = new HistoryDAO(getApplicationContext());
		File folder2 = new File(Environment.getExternalStorageDirectory()
				+ "/tesseract-ocr/tessdata");
		if (!folder2.exists())
			Log.d("----", "create tessdata");
		folder2.mkdir();
		/*
		 * create directory store text ocr
		 */
		File folder = new File(Environment.getExternalStorageDirectory()
				+ "/ocr-result");
		if (!folder.exists())
			folder.mkdir();
		/*
		 * construct list language
		 */
		if (loaded == false) {
			Language engLanguage = new Language("English", DATA_PATH, "eng");
			// Language jpnLanguage = new Language("Japanese", DATA_PATH,
			// OCRCostant.JAPANESE);
			Language vietLanguage;
			if (OCR_MODE == 2) {
				Log.d("--------OCRmode", "quickly");
				vietLanguage = new Language("VietNamese", DATA_PATH,
						OCRCostant.VIE_PACKCODE_QUICKLY);
			} else if (OCR_MODE == 1) {
				Log.d("--------OCRmode", "normal");
				vietLanguage = new Language("VietNamese", DATA_PATH,
						OCRCostant.VIE_PACKCODE_NORMAL);
			} else {
				Log.d("--------OCRmode", "accurate");
				vietLanguage = new Language("VietNamese", DATA_PATH,
						OCRCostant.VIE_PACKCODE_ACCURATE);
			}

			LanguageContext.addLanguage(engLanguage);
			LanguageContext.addLanguage(vietLanguage);
			// LanguageContext.addLanguage(jpnLanguage);
			loaded = true;
		}

		/*
		 * find view by id
		 */
		btnSelectAlbum = (Button) findViewById(R.id.img_gallery);
		btnSelectCamera = (Button) findViewById(R.id.img_camera);
		imgMenu = (ImageView) findViewById(R.id.img_menu);
		imgBanner = (ImageView) findViewById(R.id.img_banner);
		layoutAdmod = (LinearLayout) findViewById(R.id.layout_admod);
		if (Locale.getDefault().getLanguage().trim().equals("vi")) {
			imgBanner.setImageResource(R.drawable.demo_vn);
		}
		/*
		 * create button layout
		 */

		btnSelectAlbum.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent gallaryIntent = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
				startActivityForResult(gallaryIntent,
						OCRCostant.ACTIVITY_SELECT_IMAGE);
			}
		});

		btnSelectCamera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent,
						OCRCostant.CAMERA_PIC_REQUEST);
			}
		});

		/*
		 * main menu
		 */
		imgMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PopupMenu popup = new PopupMenu(MainActivity.this, v);
				MenuInflater inflater = popup.getMenuInflater();
				inflater.inflate(R.menu.main_activity_menu, popup.getMenu());
				popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
					public boolean onMenuItemClick(MenuItem item) {
						Log.d("---------------------OCR",
								"OnMenuItemClickListener");
						switch (item.getItemId()) {
						case R.id.action_show_history:
							Intent intent = new Intent(MainActivity.this,
									HistoryActivity.class);
							startActivity(intent);
							break;
						case R.id.action_show_tip:
							Intent intent2 = new Intent(MainActivity.this,
									TrickAndTips.class);
							startActivity(intent2);
							break;
						}

						return true;
					}
				});

				popup.show();// showing popup menu
			}
		});

		/*
		 * admod layout
		 */
		// Create an ad.
		adView = new com.google.android.gms.ads.AdView(this);
		adView.setAdSize(AdSize.BANNER);
		adView.setAdUnitId(AD_UNIT_ID);
		layoutAdmod.addView(adView);
		// get test ads on a physical device.
		// AdRequest adRequest = new AdRequest.Builder()
		// .addTestDevice("android-31046cf4bc406ccd").build();
		// adView.loadAd(adRequest);

		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
	}

	public void showPopup(View v) {
		PopupMenu popup = new PopupMenu(MainActivity.this, v);
		MenuInflater inflater = popup.getMenuInflater();
		inflater.inflate(R.menu.main_activity_menu, popup.getMenu());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String imgPath = "";
		switch (requestCode) {
		/*
		 * on select from album
		 */
		case 111:
			if (resultCode == RESULT_OK) {
				imgUri = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(imgUri,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				imgPath = cursor.getString(columnIndex);
				cursor.close();

			}
			break;
		/*
		 * on select from camera
		 */
		case 1337: {
			try {
				imgUri = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(imgUri,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				imgPath = cursor.getString(columnIndex);
				cursor.close();

			} catch (Exception ex) {

			}

		}
			break;

		default:
			break;
		}
		if (imgPath.length() > 0) {
			try {
				AdjustImgAsyntak adjustImgAsyntak = new AdjustImgAsyntak();
				adjustImgAsyntak.execute(imgPath);
			} catch (Exception ex) {

			}
		}
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// // TODO Auto-generated method stub
	// getMenuInflater().inflate(R.menu.main_activity_menu, menu);
	// return true;
	// }
	//
	// @Override
	// public boolean onOptionsItemSelected(MenuItem item) {
	// // TODO Auto-generated method stub
	// if (item.getItemId() == R.id.action_show_history) {
	// Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
	// startActivity(intent);
	// }
	// return true;
	// }

	/*
	 * adjust image
	 */
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				Intent intent = new Intent(MainActivity.this,
						ImageActivity.class);
				startActivity(intent);
			}
		};
	};

	/*
	 * calculate brightness bitmap
	 */
	public int caculateB(Bitmap bitmap) {
		long result = 0;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		if (width * height > OCRCostant.MAX_SIZE_UN_PROCESS)
			return 2;// img too big ---> not process
		Log.i("----------------thoainguyen caculateB img width:",
				String.valueOf(width));
		Log.i("-----------------thoainguyen caculateB img height:",
				String.valueOf(height));
		int r, g, b;
		int count = 0;
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				int pixel = bitmap.getPixel(i, j);
				r = Color.red(pixel);
				g = Color.green(pixel);
				b = Color.blue(pixel);
				float y = 0.2126f * r + 0.7152f * g + 0.0722f * b;
				result += y;
				count++;
				// Log.d("------------thoainguyen caculateB result:",
				// String.valueOf(result));
				// Log.d("------------thoainguyen caculateB count:",
				// String.valueOf(count));
			}
		}

		float kq = result / count;
		if (kq < 100)
			return -1;// too dark to process
		if (kq > 200)
			return 2;// ok or too light
		Log.d("---thoainguyen----brightness:", String.valueOf(kq));

		return 1;// normal --> process
	}

	class AdjustImgAsyntak extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog.setCancelable(false);
			progressDialog.setIndeterminate(true);
			progressDialog.show();
		}

		@Override
		protected Bitmap doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			try {
				/*
				 * luu 2 bitmap, 1 img goc(hien thi len imgview), 1 img da dc xu
				 * ly anh
				 */
				String path = arg0[0];
				ImageActivity.IMG_PATH = path;
				ImageActivity.PROCESSED_IMG = BitmapFactory
						.decodeFile(ImageActivity.IMG_PATH);
				ExifInterface exif = null;
				try {
					exif = new ExifInterface(ImageActivity.IMG_PATH);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Toast.makeText(getApplicationContext(), "Loi khi mo hình",
							Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
				int exifOrientation = exif.getAttributeInt(
						ExifInterface.TAG_ORIENTATION,
						ExifInterface.ORIENTATION_NORMAL);

				int rotate = 0;

				switch (exifOrientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					rotate = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					rotate = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					rotate = 270;
					break;
				}

				if (rotate != 0) {
					int w = ImageActivity.PROCESSED_IMG.getWidth();
					int h = ImageActivity.PROCESSED_IMG.getHeight();

					// Setting pre rotate
					Matrix mtx = new Matrix();
					mtx.preRotate(rotate);

					// Rotating Bitmap & convert to ARGB_8888, required by tess
					ImageActivity.PROCESSED_IMG = Bitmap
							.createBitmap(ImageActivity.PROCESSED_IMG, 0, 0, w,
									h, mtx, false);
				}
				Log.d("----------@@@@@@-------", "converted img");
				IMG_BRIGHTNESS_NUM = caculateB(ImageActivity.PROCESSED_IMG);
				if (IMG_BRIGHTNESS_NUM == 1) {
					ImageActivity.ORGINAL_IMG = BitmapFactory
							.decodeFile(ImageActivity.IMG_PATH);
					ProcessImgUtil imgUtil = new ProcessImgUtil();
					ImageActivity.PROCESSED_IMG = imgUtil
							.processImg(ImageActivity.PROCESSED_IMG);

				}

				return ImageActivity.PROCESSED_IMG;
			} catch (Exception ex) {
				AlertDialog.Builder builder1 = new AlertDialog.Builder(
						getApplicationContext());
				builder1.setTitle("Error");
				builder1.setMessage("Your image is too hard to process OCR.");
				builder1.setCancelable(true);
				builder1.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				builder1.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = builder1.create();
				alertDialog.show();
				return null;
			}

		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (progressDialog != null && progressDialog.isShowing())
				progressDialog.dismiss();
			if (result != null)
				handler.sendEmptyMessage(0);

		}

	}
}
